#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Checker CLF
# author : zyh
# date : 2007.11.6


import pygtk
import gobject
import time,sys,cookielib,urllib2
import gtk
import search


all_area={"社区公告栏":"new","社区服务台":"uglyduck","新闻与评论":"linuxnews", \
"自由软件杂谈":"linuxtalk","IT人生":"life","linux软件快递":"software","翻译作坊":"Tworkshop", \
"Linux图书与评论":"tcl","招聘和求职":"job","GNU Emacs XEmacs":"vim", \
"Linux中文环境与中文化":"chinese","Linux桌面与办公软件":"office","Linux多媒体与娱乐版":"game", \
"自由之窗":"mozilla","笔记本电脑上的Linux":"laptop","Gentoo":"gentoo", \
"Debian一族":"debian","网络管理技术":"nm","Linux安装与入门":"newbie", \
"WEB服务器和FTP服务器":"web","域名服务器和邮件服务器":"dns","Linux防火墙和代理服务器应用":"proxy", \
"文件及打印服务器":"samba","技术培训与认证":"training","Linux内核技术":"linuxK" ,\
"Linux嵌入技术":"embedded","Linux设备驱动程序":"driver","Linux集群技术":"cluster", \
"Linux平台数据库":"db","系统和网络安全":"security","CPU与编译器":"cpu",\
"系统计算研究所专栏":"school","Linux下的GUI软件开发":"kylix","C/C++编程版":"program", \
"php技术":"php3","Java/jsp技术":"java","Shell编程技术":"vrml", \
"Perl编程":"perl","Python编程":"python","XML/web Service技术":"xml", \
"永远的UNIX":"unix","FreeBSD世界":"bsd"}

class conf_dialog:

    def destroy(self, widget, data=None):
        return False
    def delete_event(self, widget, event, data=None):
        return False
    
    def response_checked (self,widget,data):
        if widget.get_active():
            self.target_area.add(data)
        else:
            self.target_area.remove(data)


    def __init__(self,now_area,interval):
        global all_area
        self.all_area=all_area
        self.target_area=set()

        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_title("配置")
        self.window.connect("delete_event", self.delete_event)
        self.window.connect("destroy", self.destroy)
      
        self.listconn = gtk.Table( rows=24, columns=4 )

        tlb1 = gtk.Label(" 版面名字 ")
        tlb1.set_justify(gtk.JUSTIFY_CENTER)
        tlb1.show()

        tlb2 = gtk.Label("是否关注")
        tlb2.set_justify(gtk.JUSTIFY_CENTER)
        tlb2.show()

        self.listconn.attach( tlb1, 0, 1, 0, 1 )
        self.listconn.attach( tlb2, 1, 2, 0, 1 )
        tlb3 = gtk.Label(" 版面名字 ")
        tlb3.set_justify(gtk.JUSTIFY_CENTER)
        tlb3.show()

        tlb4 = gtk.Label("是否关注")
        tlb4.set_justify(gtk.JUSTIFY_CENTER)
        tlb4.show()

        self.listconn.attach( tlb3, 2, 3, 0, 1 )
        self.listconn.attach( tlb4, 3, 4, 0, 1 )

        self.rb = []

        i=0;
        left=0
        right=1
        for area_name in self.all_area.keys():
            lt = gtk.Label(area_name)
            lt.show()
            self.listconn.attach( lt, left, right, i+1, i+2 )
            bt = gtk.CheckButton()
            if self.all_area[area_name] in now_area:
                bt.set_active(True)
                self.target_area.add(area_name)
            bt.show()
            bt.connect( "toggled", self.response_checked, area_name )
            self.listconn.attach( bt, left+1, right+1, i+1, i+2 )
            self.listconn.show()
            
            if i==20:
                i=0
                left=2
                right=3
                
            else:
                i+=1
        i=21
        lt=gtk.Label("每隔多少分钟检查一次?")
        lt.show()
        self.listconn.attach(lt,0,1,i+1,i+2)

        self.interval_edit=gtk.Entry(max=4)
        self.interval_edit.set_width_chars(4)
        self.interval_edit.set_text(interval)
        self.listconn.attach(self.interval_edit,1,2,i+1,i+2)
        self.interval_edit.show()
        i+=1
        
        self.b1 = gtk.Button( None, gtk.STOCK_OK )
        self.b1.show()

        self.b2 = gtk.Button( None, gtk.STOCK_CANCEL )
        self.b2.show()

        self.listconn.attach(self.b1,0,1,i+1,i+2)
        self.listconn.attach(self.b2,0,1,i+2,i+3)

        self.window.add(self.listconn)


    def main (self):
        self.window.show()
        

class trayicon:
    def __init__ (self):
        self.interval=60000 #check in every minute...maybe too serious?
        self.sicon=gtk.StatusIcon()
        self.sicon.set_from_stock(gtk.STOCK_INFO)
        
        self.tooltip="no news is good news."
        self.sicon.set_tooltip(self.tooltip)
        self.li=[]
        self.newpost={}
        self.newthread={}
        self.sicon.connect("activate",self.on_leftclick)
        self.sicon.connect("popup-menu",self.make_menu)

    def make_menu (self,si,button,time):
        menu=gtk.Menu()
        item=gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        menu.append(item)
        item.connect("activate",self.menu_response,"configure")
        item.show()
        item=gtk.ImageMenuItem(gtk.STOCK_QUIT)
        menu.append(item)
        item.connect("activate",self.menu_response,"exit")
        item.show()
        menu.popup(None, None, gtk.status_icon_position_menu,
                        button, time, si)

    def menu_response (self,widget,string):
        if string=="configure":
            dialog=conf_dialog(self.li,str(self.interval/(1000*60)))
            self.dialog=dialog
            dialog.b1.connect("clicked",self.config_dialog_ok)
            dialog.b2.connect("clicked",self.config_dialog_cancel,)
            dialog.main()
        elif string=="exit":
            gtk.main_quit()
        
    def config_dialog_ok (self,widget):
        interval=self.dialog.interval_edit.get_text()
        try:
            self.interval=int(interval)*1000*60
        except ValueError:
            error_dialog=gtk.MessageDialog(type=gtk.MESSAGE_ERROR, 
                message_format="指定的检查间隔时间有误",
                buttons=gtk.BUTTONS_CLOSE)
            error_dialog.show()
            return
        self.li=[]
        for item in self.dialog.target_area:
            self.li.append(self.dialog.all_area[item])
        self.dialog.window.destroy()

    def config_dialog_cancel (self,widget):
        self.dialog.window.destroy()
       

    def on_leftclick (self,arg):
        self.sicon.set_blinking(False)

    def get_whole_name (self,addr):
        global all_area
        for item in all_area.items():
            if item[1]==addr:
                return item[0]
        return None

    def check (self):
        global all_area
        changed=0
        rstpost=""
        rstthread=""
        if len(self.li)==0:
            self.tooltip="No news is good news."
        else:
            for area in self.li:
                if self.newpost[area]!='0':
                    whole_name=self.get_whole_name(area)
                    changed=1
                    rstpost+="%s版有 %s个新帖子\n"%(whole_name,self.newpost[area])
                if self.newthread[area]!='0':
                    changed=1
                    rstthread+="%s版有%s个新主题.\n"%(whole_name,self.newthread[area])
            if changed:
                self.tooltip=rstpost+rstthread
                self.sicon.set_blinking(True)
        self.sicon.set_tooltip(self.tooltip)


    def main (self):
        gtk.main()

def checker ():
    global icon
    if len(icon.li)==0:
	    id=gobject.timeout_add(icon.interval,checker)
	    return
  
    cookiejar=cookielib.MozillaCookieJar()
    try:
        cookiejar.load('cookies.txt')
    except IOError:
        print "I can't find cookies.txt"
        return
    httpcookie=urllib2.HTTPCookieProcessor(cookiejar)
    opener=urllib2.build_opener(httpcookie)
    fobj=opener.open("http://www.linuxforum.net/forum/ubbthreads.php")
    htm=fobj.read()
    fobj.close()
    opener.close()

    icon.newpost,icon.newthread=search.feed(htm,icon.li)
    icon.check()
    
    id=gobject.timeout_add(icon.interval,checker)

if __name__=="__main__":
    try:
        fcookie=file("cookies.txt","r")
    except IOError:
        print "The cookies.txt should be put in the same dir with me."
        sys.exit(1)
        
    fcookie.close()
    icon=trayicon()
    
    id=gobject.timeout_add(1*60*1000,checker) #check in 1 minute when starting
    icon.main()


    





      

